import guid from './guid'

/**
 * value ：要搜索的值
 * array ： 被搜索的数组
 * type ： 类型，true全等 ，false非全等(默认)
 */
function inArray(value, array, type = false) {
	let ok = -1;
	for (var i = 0; i < array.length; i++) {
		if (value == array[i]) {
			++ok;
		}
	}
	if (type) {
		return ok == array.length
	} else {
		return ok >= 0;
	}
}

function getChildrenByList(key, children, filter = undefined) {
	let list = [];
	for (let i = 0; i < children.length; i++) {
		let item = children[i];
		if (filter != undefined) {
			if (filter(item) == false) {
				continue;
			}
		}
		list.push(item);
		if (item[key] == undefined) {
			continue;
		}
		if (item[key] == null) {
			continue;
		}
		if (typeof item[key] != 'object') {
			continue;
		}
		let items = getChildrenByList(key, item[key], filter);
		for (let j = 0; j < items.length; j++) {
			list.push(items[j]);
		}
	}
	return list;
}

function deepCopy(value) {
	switch (Object.prototype.toString.call(value)) {
		case '[object Null]':
			return null;
		case '[object Undefined]':
			return undefined;
		case '[object String]':
			return value;
		case '[object Object]':
			let obj = {}
			for (let i = 0; i < Object.keys(value).length; i++) {
				obj[Object.keys(value)[i]] = deepCopy(value[Object.keys(value)[i]])
			}
			return obj;
		case '[object Array]':
			let arr = []
			for (let i = 0; i < value.length; i++) {
				arr.push(deepCopy(value[i]))
			}
			return arr;
		default:
			return value;
	}
}

function deepAssignCopy(...objects) {
    // 初始化结果对象，使用第一个对象（如果有）作为起点  
    let result = {};  
    if (objects.length > 0 && typeof objects[0] === 'object' && objects[0] !== null) {  
        result = { ...objects[0] };  
    }  
  
    // 遍历剩余的每个对象，并将它们合并到结果对象中  
    for (let i = 1; i < objects.length; i++) {  
        const obj = objects[i];  
        for (const key in obj) {  
            if (obj.hasOwnProperty(key)) {  
                if (  
                    typeof result[key] === 'object' && result[key] !== null &&  
                    typeof obj[key] === 'object' && obj[key] !== null  
                ) {  
                    // 如果两个属性都是对象，则递归合并  
                    result[key] = deepAssignCopy(result[key], obj[key]);  
                } else {  
                    // 否则，直接覆盖结果对象中的属性  
                    result[key] = obj[key];  
                }  
            }  
        }  
    }  
  
    return result;  
}

export default {
	guid: guid,
	inArray,
	getChildrenByList,
	deepCopy,
	deepAssignCopy,
}